﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Windows.Forms;
using Microsoft.VisualStudio.CommandBars;
using Microsoft.TeamFoundation.VersionControl.Client;
using EnvDTE;
using EnvDTE80;

namespace TFSPlus.Commands
{
    public class GetVersionFromHistory : IAddinUICommand
    {

        #region IAddinUICommand Members

        public void UISetup(EnvDTE80.DTE2 applicationObject, EnvDTE.AddIn addInInstance, EnvDTE80.Commands2 commands, object[] contextGUIDS)
        {
            // Get Version From History
            Command getVersionFromHistoryCommand = commands.AddNamedCommand2(addInInstance, "GetVersionFromHistory", "Get This Version", "Retrieves the specified version for the item", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
            if (getVersionFromHistoryCommand != null)
            {
                CommandBarControl getSpecificVersionButtonFolder = Connect.GetCommandBarControl("Folder", "Get Specific Version...", null);
                int faceIdGetSpecific = (getSpecificVersionButtonFolder != null && getSpecificVersionButtonFolder is CommandBarButton) ? ((CommandBarButton)getSpecificVersionButtonFolder).FaceId : 59;

                // Add command to History Tool Window shortcut menu
                CommandBar sourceControlHistoryCmdBar = ((CommandBars)applicationObject.CommandBars)["Source Control History"];
                CommandBarButton sourceControlHistoryShortcutCtrl = (CommandBarButton)getVersionFromHistoryCommand.AddControl(sourceControlHistoryCmdBar, sourceControlHistoryCmdBar.Controls.Count);
                sourceControlHistoryShortcutCtrl.FaceId = faceIdGetSpecific;
            }
        }

        public void Startup(EnvDTE80.DTE2 applicationObject, EnvDTE.AddIn addInInstance)
        {
            
        }

        public EnvDTE.vsCommandStatus QueryStatus()
        {
            if (Connect.VersionControlExt == null || Connect.VersionControlExt.History == null)
                return vsCommandStatus.vsCommandStatusInvisible;

            Changeset[] changesets = Connect.VersionControlExt.History.SelectedItems;
            if (changesets.Length == 1)
                return vsCommandStatus.vsCommandStatusEnabled | vsCommandStatus.vsCommandStatusSupported;
            else
                return vsCommandStatus.vsCommandStatusInvisible | vsCommandStatus.vsCommandStatusSupported;
        }

        public void Exec()
        {
            if (Connect.VersionControlExt.Explorer == null)
                return;

            Workspace workspace = Connect.VersionControlExt.Explorer.Workspace;
            if (workspace == null)
                return;

            Changeset[] changesets = Connect.VersionControlExt.History.SelectedItems;
            if (changesets.Length != 1)
            {
                MessageBox.Show("Select a single version in the history window.");
                return;
            }

            int cs = changesets[0].ChangesetId;

            string filePath = "";
            foreach (Window w in Connect.ApplicationObject.Windows)
            {
                if (w.Caption.StartsWith("History - "))
                    filePath = w.Caption.Substring("History - ".Length);
            }

            if (!String.IsNullOrEmpty(filePath) && cs > 0)
            {
                string serverPath, localPath;
                TFSPlusCommon.GetServerPathLocalPath(workspace, filePath, out serverPath, out localPath);
                if (serverPath == null || localPath == null)
                {
                    TFSPlusCommon.OutputGeneralString("Unable to resolve workspace mappings for item " + filePath);
                    return;
                }

                Item item = workspace.VersionControlServer.GetItem(serverPath);
                if (item.ItemType == ItemType.File)
                {
                    bool isCheckedOutByMe = TFSPlusCommon.IsCheckedOutByMe(workspace, serverPath);

                    string question = "";
                    if (isCheckedOutByMe)
                        question = serverPath + " is checked out. Getting this version will effectively rollback this file to the specified version in your local workspace. Are you sure you want to do this?";
                    else if (File.Exists(localPath) && (File.GetAttributes(localPath) & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                        question = localPath + " is writeable. Are you sure you want to get a different version of this file?";
                    //else
                    //    question = "Forcably get changeset " + cs.ToString() + " of " + serverPath + "?";

                    if (!String.IsNullOrEmpty(question))
                    {
                        if (MessageBox.Show(question, "Get", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }

                    if (isCheckedOutByMe)
                    {
                        // Revert to old version using Download
                        workspace.VersionControlServer.DownloadFile(serverPath, 0, new ChangesetVersionSpec(cs), localPath);
                    }
                    else
                    {
                        workspace.Get(new string[] { filePath }, new ChangesetVersionSpec(cs), RecursionType.Full, GetOptions.GetAll | GetOptions.Overwrite);
                    }
                }
                else
                {
                    // Folder type
                    string question = "";
                    question = "Forcably get version " + cs.ToString() + " of all files below the folder " + filePath + "?";

                    if (!String.IsNullOrEmpty(question))
                    {
                        if (MessageBox.Show(question, "Get", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }

                    workspace.Get(new string[] { filePath }, new ChangesetVersionSpec(cs), RecursionType.Full, GetOptions.GetAll | GetOptions.Overwrite);
                }
            }
        }

        public void Disconnect(DTE2 applicationObject, AddIn addInInstance)
        {
        }

        #endregion
    }
}
